package com.water.app.Interceptor;

import com.water.app.Constant;
import com.water.app.Controller.account.LoginController;
import com.water.app.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger log= LoggerFactory.getLogger(LoginController.class);

    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }
    // 在请求处理之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7).trim(); // 去除前缀和可能的空格
        } else {
            // 无有效令牌，直接返回未登录
            return false;
        }

        Integer isValid = JwtUtil.parseJwt(token);
        String token2 = stringRedisTemplate.opsForValue().get(Constant.LOGIN_USER + isValid);
        if(isValid!=null&&isValid>0&&token2!=null&&!token.isEmpty()&&token2.equals(token)){
            log.info("用户已登录，放行");
            Constant.THREAD_LOCAL.set(JwtUtil.parseJwt(token));
            return true;
        }else{
            log.info("用户未登录，拦截");
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":\"0\",\"msg\":\"用户未登录\",\"data\":\"null\"}");
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Constant.THREAD_LOCAL.remove();
    }
}
